package cn.nawang.ebeim.api.repository.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.nawang.ebeim.api.comm.PageList;
import cn.nawang.ebeim.api.comm.Pages;
import cn.nawang.ebeim.api.repository.QueryBaseRepository;

/**
 * @ClassName: QueryBaseRepositoryImpl
 * @Description: TODO
 * @author 许炜毅
 * @date 2015年8月5日 下午4:18:17
 * @version v1.0
 */
@Repository
public class QueryBaseRepositoryImpl implements QueryBaseRepository{

  @Autowired
  private EntityManagerFactory entityManagerFactory;
  
  @Override
  public List<Object[]> findAll(String sql) {
    List objList = null;
    EntityManager em = entityManagerFactory.createEntityManager();
    try{
      Query query =  em.createNativeQuery(sql);
      objList = query.getResultList();
    }catch(Exception ex){
      ex.printStackTrace();
    }finally{
      em.close();
    }
    return objList;
  }

  @Override
  public int countAllData(String sql) {
    int count = 0;
    EntityManager em = entityManagerFactory.createEntityManager();
    try{
      Query query =  em.createNativeQuery(sql);
      List objList = query.getResultList();
      if(objList!=null && objList.size()>0){
        count = Integer.valueOf(objList.get(0).toString());
      }
    }catch(Exception ex){
      ex.printStackTrace();
      
    }finally{
      em.close();
    }
    return count;
  }

  @Override
  public PageList findAllByPaging(String sql, Pages page) {
    PageList pl = null;
    EntityManager em = entityManagerFactory.createEntityManager();
    try{      
      Query query =  em.createNativeQuery(sql);
      query.setFirstResult(page.getStartPos());
      query.setMaxResults(page.getPageSize());
      List objList = query.getResultList();
      
      pl = new PageList();
      pl.setObjList(objList);
      pl.setPage(page);
      pl.setSuccess(true);
    }catch(Exception ex){
      ex.printStackTrace();
    }finally{
      em.close();
    }
    return pl;
  }

}
